package com.ruoyi.quartz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.wx.WechatUtils;
import com.ruoyi.quartz.service.IWechatAppScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

/**
 * 微信相关任务 服务层
 *
 * @author wanghc
 */
@Slf4j
@Service
public class WechatAppScheduleServiceImpl implements IWechatAppScheduleService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 功能描述:   从微信公共服务器获取access_token
     *
     * @Author wanghc
     * @Date 2022/08/21 12:06
     * @param
     * @return void
     */
    @Override
    public void getAccessToken() {
        log.info(">>>>>>>>>>>>>>>>>执行定时刷新小程序access_token时间: " + LocalDateTime.now());
        // 获取access_token:通过自定义工具类组合出小程序需要的获取access_token的url
        String requestUrl = WechatUtils.getMiniprogramAccessToken();
        log.info(">>>>>>>>>>>>>>>>>获取openid接口为：" + requestUrl);
        JSONObject sessionData = HttpUtils.httpsRequest(requestUrl, "GET", null);
        if (null != sessionData && StringUtils.isNotEmpty(sessionData.getString(CacheConstants.ACCESS_TOKEN))) {
            log.info(sessionData.toJSONString());
            redisCache.setCacheObject(CacheConstants.getAccessTokenCacheKey(), sessionData.getString(CacheConstants.ACCESS_TOKEN));
            log.info(">>>>>>>>>>>>>>>>>获取接口调用凭证：" + redisCache.getCacheObject(CacheConstants.getAccessTokenCacheKey()));
        }
    }
}
